package com.eclipse.e0113_网络编程.多人聊天_服务器负责转发;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {

	static int port = 8081;
	static int num = 1;
	static HashMap<String, ServerHandler> allServerHandler = new HashMap<>();

	public static void main(String[] args) throws Exception {
		
		ServerSocket server = new ServerSocket(port);
		System.out.println("开始在" + port + "端口监听：");

		// 持续地监听连接的请求
		while (true) {
			//阻塞 等待连接
			Socket socket = server.accept();
			System.out.println("有客戶端连接进来。。。。。。");
			// 只要有连接，就创建一个线程，这个线程负责这个客户端
			ServerHandler serverHandler = new ServerHandler(socket);
			serverHandler.setName(num++ + "");
			allServerHandler.put(serverHandler.getName(), serverHandler);
			serverHandler.start();
		}
	}
}


//转发消息
class ServerHandler extends Thread {

	private Socket socket;
	BufferedWriter out;
	BufferedReader in;

	public ServerHandler(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		try {
			out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			//表明对应的客户端是谁 客户端第一条信息会输入自己的姓名
			String name = in.readLine();
			System.out.println(name);
			
			//移除map集合里的默认数字name
			Server.allServerHandler.remove(getName());
			//替换为输入的名字
			Server.allServerHandler.put(name, this);
			setName(name);

			//读取当前客户端对应的消息，然后根据客户端名称转发
			String message = null;

			int atIndex = 0;

			//消息里@前面的 接收者名字
			String otherClientNum;
			do {
				//输入的消息
				message = in.readLine();

				System.out.println("发送者"+getName() + ":" + message);

				atIndex = message.indexOf("@");

				otherClientNum = message.substring(0, atIndex);

				System.out.println("接受者otherClientNum:" + otherClientNum);

				//获取接受者对象
				ServerHandler otherClientServerHandler = Server.allServerHandler.get(otherClientNum);

				otherClientServerHandler.sendMessage(message);

			} while (!message.equals("88"));

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				// 关闭资源
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				if (socket != null) {
					socket.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param message 要发送的消息
	 */
	public void sendMessage(String message) {
		try {
			out.write(message + "\r\n");
			out.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
